package repeat.personal.util;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;


/**
 * 解析execl
 *
 * @author: Zhanggq
 * @date: 2019/5/15 9:34
 **/
public class ExeclPoiUtil {
    public static void main(String[] args) {
        String filePath = "D:\\test.xlsx";
        List<Map<String, String>> list = ExeclPoiUtil.execlToMap(filePath);
        //遍历解析出来的list
        for (Map<String, String> map : list) {
            for (Entry<String, String> entry : map.entrySet()) {
                System.out.print(entry.getKey() + ":" + entry.getValue() + ",");
            }
            System.out.println();
        }
    }

    /**
     * 读取execl 并转成map
     * @param filePath 文件路径（如：D:\\test.xlsx）
     * @return
     */
    public static List<Map<String, String>> execlToMap(String filePath) {
        String[] columns = new String[100];
        Workbook wb = null;
        Sheet sheet = null;
        Row row = null;
        List<Map<String, String>> list = null;
        wb = readExcel(filePath);
        if (wb != null) {
            //用来存放表中数据
            list = new ArrayList<Map<String, String>>();
            //获取第一个sheet
            sheet = wb.getSheetAt(0);
            //获取最大行数
            int rownum = sheet.getPhysicalNumberOfRows();
            if(rownum <= 0){
                return null;
            }
            //获取第一行 即列的值
            row = sheet.getRow(0);
            //获取最大列数
            int colnumMax = row.getPhysicalNumberOfCells();
            // 把列的值放到进字符串数组
            for (int j = 0; j < colnumMax; j++) {
                //cellData = (String) getCellFormatValue(row.getCell(j));
                String cellData = null;
                Object result = getValue(row.getCell(j));
                if(result != null){
                    cellData = result.toString();
                }
                columns[j] = cellData;
            }

            for (int i = 1; i < rownum; i++) {
                Map<String, String> map = new LinkedHashMap<String, String>();
                row = sheet.getRow(i);
                if (row != null) {
                    for (int j = 0; j < colnumMax; j++) {
                        //cellData = (String) getCellFormatValue(row.getCell(j));
                        String cellData = null;
                        Object result = getValue(row.getCell(j));
                        if(result != null){
                            cellData = result.toString();
                        }
                        map.put(columns[j], cellData);
                    }
                } else {
                    break;
                }
                list.add(map);
            }
        }
        return list;
    }

    // 读取excel
    private static Workbook readExcel(String filePath) {
        Workbook wb = null;
        if (filePath == null) {
            return null;
        }
        String extString = filePath.substring(filePath.lastIndexOf("."));
        InputStream is = null;
        try {
            is = new FileInputStream(filePath);
            if (".xls".equals(extString)) {
                return wb = new HSSFWorkbook(is);
            } else if (".xlsx".equals(extString)) {
                return wb = new XSSFWorkbook(is);
            } else {
                return wb = null;
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return wb;
    }

    private static Object getValue(Cell cell) {
        if(cell == null){
            return null;
        }

        Object obj = null;
        switch (cell.getCellTypeEnum()) {
            case BOOLEAN:
                obj = cell.getBooleanCellValue();
                break;
            case ERROR:
                obj = cell.getErrorCellValue();
                break;
            case NUMERIC:
                //obj = cell.getNumericCellValue();
                obj = new DecimalFormat("#").format(cell.getNumericCellValue());
                break;
            case STRING:
                obj = cell.getStringCellValue();
                break;
            default:
                break;
        }
        return obj;
    }

    // 旧的方法
    private static Object getCellFormatValue(Cell cell) {
        Object cellValue = null;
        if (cell != null) {
            //判断cell类型
            switch (cell.getCellType()) {
                case Cell.CELL_TYPE_NUMERIC: {
                    cellValue = cell.getRichStringCellValue().getString();
                    break;
                }
                case Cell.CELL_TYPE_FORMULA: {
                    //判断cell是否为日期格式
                    if (DateUtil.isCellDateFormatted(cell)) {
                        //转换为日期格式YYYY-mm-dd
                        cellValue = cell.getDateCellValue();
                    } else {
                        //数字
                        //cellValue = String.valueOf(cell.getNumericCellValue());
                        cellValue = new DecimalFormat("#").format(cell.getNumericCellValue());
                    }
                    break;
                }
                case Cell.CELL_TYPE_STRING: {
                    cellValue = cell.getRichStringCellValue().getString();
                    break;
                }
                default:
                    cellValue = "";
            }
        } else {
            cellValue = "";
        }
        return cellValue;
    }
}
